<template>
  <div class="login-page">
    <div class="login-page-left"></div>
    <div class="login-page-right">
      <div class="login-page-right-logo">
        <img src="/logo.png" />
      </div>
      <div class="login-page-right-content">
        <div class="login-page-right-content__mini-title">欢迎使用</div>
        <div class="login-page-right-content__title">{{ title }}</div>
        <div class="login-page-right-content-form">
          <!--     账号密码登录     -->
          <t-space direction="vertical" class="w-300px" v-if="loginType === 'password'">
            <t-input
              size="large"
              placeholder="账号"
              clearable
              v-model="loginForm.username"
            ></t-input>
            <t-input
              size="large"
              placeholder="密码"
              clearable
              type="password"
              v-model="loginForm.password"
            ></t-input>
            <div class="flex gap-6px flex-items-center">
              <t-input
                size="large"
                placeholder="验证码"
                clearable
                class="w-189px!"
                v-model="loginForm.code"
              ></t-input>
              <img :src="codeImg" class="h-40 w-107px cursor-pointer" @click="getCode" />
            </div>
            <div class="flex justify-between flex-items-center">
              <t-checkbox v-model="loginForm.rememberMe">记住密码</t-checkbox>
              <div class="cursor-pointer font-size-14 c-#0052d9">忘记密码</div>
            </div>
            <t-button class="w-100%" :loading="loading" @click="login">登录</t-button>
            <t-button ghost class="w-100%" @click="loginType = 'sms'">短信登录</t-button>
          </t-space>
          <!--     短信验证码登录     -->
          <t-space direction="vertical" class="w-100%" v-if="loginType === 'sms'">
            <t-input
              size="large"
              placeholder="手机号"
              clearable
              v-model="loginForm.username"
            ></t-input>
            <div class="flex gap-6px flex-items-center">
              <t-input
                size="large"
                placeholder="验证码"
                clearable
                style="width: calc(300px - 128px)"
                v-model="loginForm.code"
              ></t-input>
              <t-button
                size="large"
                theme="default"
                variant="outline"
                @click="getCode"
                :disabled="showSmsTime"
              >
                {{ !showSmsTime ? '获取验证码' : smsTime + '秒' }}</t-button
              >
            </div>
            <t-button class="w-100%" :loading="loading" @click="login">登录</t-button>
            <t-button ghost class="w-100%" @click="loginType = 'password'">返回</t-button>
          </t-space>
        </div>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
import { getCodeImg, phoneIsRegister, sendSmsCode } from '@/api/system/login.ts';
import { useUserStore } from '@/store/modules/user.ts';
import { MessagePlugin } from 'tdesign-vue-next';
import TsCookie from '@/utils/ts-cookie';
import { decrypt, encrypt } from '@/utils/jsencrypt.ts';

const userStore = useUserStore();
const router = useRouter();
const route = useRoute();

const title = __APP_ENV__.VITE_APP_TITLE;
const codeImg = ref('');
const loading = ref(false);
const loginType = ref('password');
const showSmsTime = ref(false);
const smsTime = ref(0);

const loginForm = ref({
  code: '',
  loginType: '0',
  password: '',
  rememberMe: false,
  username: '',
  uuid: '',
});

/**
 * 用户登录操作（loginType 1是短信验证码登录 0是账号密码登录）
 */
const login = async () => {
  if (loginType.value === 'password') {
    if (!loginForm.value.username) {
      MessagePlugin.error('请输入用户手机号');
      return;
    } else if (!loginForm.value.password) {
      MessagePlugin.error('请输入密码');
      return;
    } else if (!loginForm.value.code) {
      MessagePlugin.error('请输入验证码');
      return;
    }
    if (loginForm.value.rememberMe) {
      TsCookie.setItem('username', loginForm.value.username);
      TsCookie.setItem('password', encrypt(loginForm.value.password));
      TsCookie.setItem('rememberMe', loginForm.value.rememberMe);
    } else {
      TsCookie.removeItem('username');
      TsCookie.removeItem('password');
      TsCookie.removeItem('rememberMe');
    }
    loading.value = true;
    loginForm.value.loginType = '0';
    userStore
      .Login(loginForm.value)
      .then(() => {
        router.push({ path: (route.query.redirect as string) || '/' });
      })
      .catch(() => {
        loading.value = false;
        getCode();
      });
  } else if (loginType.value === 'sms') {
    if (!loginForm.value.username) {
      MessagePlugin.error('请输入用户手机号');
      return;
    } else if (!loginForm.value.code) {
      MessagePlugin.error('请输入验证码');
      return;
    }
    loading.value = true;
    let query = {
      username: loginForm.value.username,
      code: loginForm.value.code,
      loginType: 1,
    };
    userStore
      .Login(query)
      .then(() => {
        router.push({ path: (route.query.redirect as string) || '/' });
      })
      .catch(() => {
        loading.value = false;
      });
  }
};

onMounted(() => {
  getCode();
  getCookie();
});
/**
 * 获取缓存在浏览器cookie里面的账号密码
 */
const getCookie = () => {
  const username = TsCookie.getItem('username');
  const password = TsCookie.getItem('password');
  const rememberMe = TsCookie.getItem('rememberMe');
  loginForm.value.username =
    username === undefined ? loginForm.value.username : (username as string);
  loginForm.value.password =
    password === undefined ? loginForm.value.password : decrypt(password as string) || '';
  loginForm.value.rememberMe = rememberMe === undefined ? false : Boolean(rememberMe);
};

/**
 * 手机验证码/图形验证码获取
 */
const getCode = async () => {
  if (loginType.value === 'password') {
    getCodeImg().then((res) => {
      codeImg.value = 'data:image/gif;base64,' + res.data.img;
      loginForm.value.uuid = res.data.uuid;
    });
  } else if (loginType.value === 'sms') {
    if (!loginForm.value.username) {
      MessagePlugin.error('请输入用户手机号');
      return;
    }
    let query = {
      phone: loginForm.value.username,
    };
    showSmsTime.value = true;
    smsTime.value = 60;
    let t = setInterval(() => {
      smsTime.value -= 1;
      if (smsTime.value < 1) {
        clearInterval(t);
        showSmsTime.value = false;
        smsTime.value = 0;
      }
    }, 1000);
    const res = await phoneIsRegister(query);
    if (res.data.code !== 200) {
      showSmsTime.value = false;
      clearInterval(t);
      MessagePlugin.error(res.data.msg || res.message);
    } else {
      sendSmsCode(query)
        .then((res) => {
          if (res.data.code !== 200) {
            MessagePlugin.error(res.data.msg);
            showSmsTime.value = false;
            clearInterval(t);
          }
        })
        .catch(() => {
          showSmsTime.value = false;
          clearInterval(t);
          MessagePlugin.error('获取验证码失败！');
        });
    }
  }
};
</script>

<style lang="scss" scoped>
.login-page {
  @apply flex;
  .login-page-left {
    @apply h-100vh w-500 flex-shrink-0;
    background-image: url(/src/assets/images/login_bg.png);
    background-position-x: 24%;
    background-position-y: 39%;
    background-repeat: no-repeat;
  }
  .login-page-right {
    @apply relative w-100%;
    .login-page-right-logo {
      @apply p32;
    }
    .login-page-right-content {
      @apply absolute
      top-50%
      left-50%;
      transform: translate(-50%, -50%);

      .login-page-right-content__mini-title {
        @apply font-size-16
        font-bold;
      }
      .login-page-right-content__title {
        @apply font-size-32
        font-bold
        mb-8;
      }
      .login-page-right-content-form {
        @apply w-280;
        :deep(.t-input) {
          background: #eee;
        }
      }
    }
  }
}
</style>
